package com.bil.socket.proxy;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;

import org.apache.commons.io.IOUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ProxyForwardServer {
  public static void main(String[] args) {
    log.info(Arrays.toString(args));
    // 获取本地监听端口、远程IP和远程端口
    int localPort = Integer.valueOf(args[0]);
    String remoteIp = args[1];
    int remotePort = Integer.valueOf(args[2]);
    ServerSocket serverSocket = null;
    try {
      // 启动本地监听端口
      serverSocket = new ServerSocket(localPort);
      log.info("端口监听成功成功！");
      Socket clientSocket = null;
      Socket remoteServerSocket = null;
      while (true) {
        try {
          // 获取客户端连接
          clientSocket = serverSocket.accept();
          remoteServerSocket = new Socket(remoteIp, remotePort);
          log.info("获取到新的客户端连接:{},创建新的连接到服务端:{}",clientSocket,remoteServerSocket);
          // 启动数据转换接口
          SendThread send = new SendThread(clientSocket, remoteServerSocket);
          send.start();
          ReceiveThread receive = new ReceiveThread(remoteServerSocket, clientSocket);
          receive.start();
        } catch (Exception ex) {
          ex.printStackTrace();
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      IOUtils.closeQuietly(serverSocket);
    }
  }
}